<template>
	<view class="page-content">
		<text class="main-text-color p-2">用户签名</text>
		<br />
		<text class="main-text-color p-2">我已阅读上述协议</text>
		<view class="form">
			<view class="form-content">
				<canvas class="form-content__canvas" canvas-id="canvas_sign" @touchstart="touchstart"
					@touchmove="touchmove" @touchend="touchend" disable-scroll="true"></canvas>
			</view>

			<view class="form-footer">
				<button class="form-footer__reset" @click="autographClick(1)">重置</button>
				<button class="form-footer__save" @click="autographClick(2)">保存</button>
				<button class="form-footer__preview" @click="autographClick(3)">预览</button>
			</view>
		</view>

	</view>
</template>
<script>
	export default {
		data() {
			return {
				canvasCtx: '', //绘图图像
				points: [], //路径点集合
				hasSign: false,
				isInit: false,
			}
		},
		mounted(query) {
		    this.canvasCtx = uni.createCanvasContext('canvas_sign', this) //创建绘图对象
		    //设置画笔样式
		    this.canvasCtx.lineWidth = 1
		    // 设置线条的端点样式
		    this.canvasCtx.lineCap = 'round'
		    // 设置线条的交点样式
		    this.canvasCtx.lineJoin = 'round'
		},
		methods: {
			touchstart: function(e) {
			    if (!this.isInit) {
			        this.isInit = true
			        this.autographClick(1);
			    }
			    let startX = e.changedTouches[0].x
			    let startY = e.changedTouches[0].y
			    let startPoint = {
			        X: startX,
			        Y: startY
			    }
			    this.points.push(startPoint)
			    //每次触摸开始，开启新的路径
			    this.canvasCtx.beginPath()
			},
			touchmove: function(e) {
			    let moveX = e.changedTouches[0].x
			    let moveY = e.changedTouches[0].y
			    let movePoint = {
			        X: moveX,
			        Y: moveY
			    }
			    this.points.push(movePoint) //存点
			    let len = this.points.length
			    if (len >= 2) {
			        this.draw() //绘制路径
			    }
			 
			},
			touchend: function() {
			    this.points = []
			    this.canvasCtx.draw(true)
			},
			draw: function() {
			    let point1 = this.points[0]
			    let point2 = this.points[1]
			    this.points.shift()
			    this.canvasCtx.moveTo(point1.X, point1.Y)
			    this.canvasCtx.lineTo(point2.X, point2.Y)
			    this.canvasCtx.stroke()
			    this.canvasCtx.draw(true)
			    this.hasSign = true
			},
			// 底部按钮点击操作
			autographClick(type) {
				let that = this
				if (type === 1) {
					//清空画布
					this.hasSign = false
					uni.getSystemInfo({
						success: function(res) {
							let canvas = uni.createSelectorQuery().in(that).select(".form-content")
							canvas.boundingClientRect(data => {

								 let canvasw = Math.ceil(data.width)
								 let canvash = Math.ceil(data.height)
								 that.canvasCtx.fillStyle = '#fff'
								 that.canvasCtx.fillRect(0, 0, canvasw, canvash)
								that.canvasCtx.draw(true)
							}).exec()
						}
					})

				} else {
					if (!this.hasSign) {
						uni.showToast({
							title: '签名不能为空',
							icon: 'none',
							duration: 2000
						})
						return
					}
					uni.getSystemInfo({
						success: function(res) {
							let canvas = uni.createSelectorQuery().in(that).select('.form-content__canvas')
							canvas.boundingClientRect(data => {
								let canvasw = Math.ceil(data.width)
								let canvash = Math.ceil(data.height)
								uni.canvasToTempFilePath({
									destWidth: canvasw,
									destHeight: canvash,
									fileType: 'jpg',
									canvasId: 'canvas_sign',
									success: function(res) {
										let path = res.tempFilePath
										console.log(res)
										// 保存图片
										if (type === 2) {
											that.uploadPic(path)
										} else if (type === 3) {
											// 预览图片
											uni.previewImage({
												urls: [path]
											})
										}
									},
									fail: (err) => {
										// http://tmp/2LVQyvzddk2R820a9009dff43323d8e7fc9ef7a8d076.jpg
										console.log('图片导出失败：', err)
									}
								},that)
								
							}).exec()
						}
					})
				}
			},

			// 图片上传处理
			uploadPic(tempFile) {
				uni.showLoading({
					title: '正在上传中...'
				})
				uni.uploadFile({
					url: getApp().globalData.baseUrl + `/supplier_applet_api.php?act=fileUploads`, // 服务器上传接口
					filePath: tempFile,
					name: 'file', // 必须填写，后台用来接收文件
					formData: {
						'user_id': uni.getStorageSync('USER_ID') // 其他POST请求中的额外参数
					},
					success: function(uploadFileRes) {
						console.log(uploadFileRes)
						let data = JSON.parse(uploadFileRes.data)
						uni.showLoading({
							title:data.msg
						})
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
					},
					fail: function(uploadFileErr) {
						console.log(uploadFileErr); // 上传失败后的操作
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	/*
    * 横屏后的适配方案
    * @param $rpx为需要转换的字号
    * @参考 https://blog.csdn.net/sdfsfsdscd/article/details/91375066
    **/
	.page-content {
		width: 100vw;
		height: calc(100vh - 160rpx);

		.form {
			display: flex;
			flex-direction: column;
			width: 100%;
			height: 100%;

			.form-content {
				width: 100%;
				height: auto;
				background: #fff;

				&__canvas {
					height: 200upx;
					width: 100vw;
				}
			}

			.form-footer {
				padding-top: 20upx;
				height: 60upx;
				width: 100%;

				display: flex;
				flex-direction: row;


				button {
					width: 20vw;

					height: 60upx;
					line-height: 60upx;
					border-radius: 20upx;
					text-align: center;
					font-size: 28upx;
					font-weight: bold;
				}

				button::after {
					border: none;
				}

				&__reset {
					color: #FD6801;
					border: 1px solid #FD6801;
				}

				&__save {
					// background-image: linear-gradient(135deg, #1BC5FF 0%, #FD6801 100%);
					background-color: #FD6801;
					color: #fff;
				}

				&__preview {
					color: #FD6801;
					border: 1px solid #FD6801;
				}
			}
		}
	}
</style>